package com.zw.yzk.kabu.data.repository;

import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.CosplayListEntity;
import com.zw.yzk.kabu.data.network.service.TopicListService;
import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.network.task.TopicListTask;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2017/1/12.
 */

public class TopicListRepository extends CommonRepository {

    private int totalCount;

    @Inject
    public TopicListRepository() {
        totalCount = TopicListTask.DEFAULT_COUNT_PER_PAGE;
    }


    @Override
    protected Observable connectServer(Task task) {
        TopicListService service = ServiceGenerator.createService(TopicListService.class);
        TopicListTask cosTask = (TopicListTask) addToken(task);

        if (cosTask.existsCount >= totalCount) {
            CosplayListEntity entity = new CosplayListEntity();
            //已经全部加载，直接返回空列表
            entity.errCode = Constant.RESULT_OK;
            entity.result.totalCount = totalCount;

            return Observable.just(entity);
        } else {
            return service.getCosplayList(cosTask.lastId, TopicListTask.DEFAULT_COUNT_PER_PAGE, cosTask.topic, cosTask.userId, cosTask.accessToken);
        }
    }

    @Override
    protected Func1<CosplayListEntity, Observable> getServerData() {
        return new Func1<CosplayListEntity, Observable>() {
            @Override
            public Observable call(CosplayListEntity entity) {
                totalCount = entity.result.totalCount;

                return Observable.just(entity);
            }
        };
    }

}
